<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer,
  DataZoomComponent
])

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  year: {
    type: Number,
    default: 2024
  }
})

const chartContainer = ref(null)
let chart: echarts.ECharts | null = null

const getMonthNames = () => {
  return ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
}

const initChart = () => {
  if (!chartContainer.value) return
  
  const monthNames = getMonthNames()
  const { inflow, outflow, netflow } = props.chartData
  
  chart = echarts.init(chartContainer.value)
  const option = {
    title: {
      text: `${props.year}年现金流分析`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      },
      show: false
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params: any) {
        let res = params[0].axisValue + '<br/>'
        params.forEach((item: any) => {
          let colorSpan = `<span style="display:inline-block;width:10px;height:10px;background:${item.color};border-radius:50%;margin-right:8px;"></span>`
          let valueStyle = item.seriesName === '净流入' ? 
            `color:${item.value >= 0 ? '#67C23A' : '#F56C6C'};font-weight:bold;` : 'font-weight:bold;'
          
          res += `<div style="display:flex;align-items:center;margin:5px 0;">
                   ${colorSpan}
                   <span>${item.seriesName}: </span>
                   <span style="${valueStyle}margin-left:5px">¥ ${item.value.toLocaleString()}</span>
                 </div>`
        })
        return res
      }
    },
    legend: {
      data: ['流入', '流出', '净流入'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: monthNames,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        min: 0,
        axisLine: {
          show: false
        },
        axisLabel: {
          formatter: (value: number) => {
            if (value >= 10000) {
              return (value / 10000) + 'w'
            }
            return value
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '净流入',
        axisLabel: {
          formatter: (value: number) => {
            if (value >= 10000) {
              return (value / 10000) + 'w'
            }
            return value
          }
        },
        axisLine: {
          show: false
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '流入',
        type: 'bar',
        barWidth: '25%',
        data: inflow,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#95D475' }
          ])
        }
      },
      {
        name: '流出',
        type: 'bar',
        barWidth: '25%',
        data: outflow,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#F56C6C' },
            { offset: 1, color: '#F89898' }
          ])
        }
      },
      {
        name: '净流入',
        type: 'line',
        yAxisIndex: 1,
        data: netflow,
        smooth: true,
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  chart && chart.resize()
}

const updateChart = () => {
  if (!chart) return
  
  chart.setOption({
    title: {
      text: `${props.year}年现金流分析`
    },
    series: [
      {
        name: '流入',
        data: props.chartData.inflow
      },
      {
        name: '流出',
        data: props.chartData.outflow
      },
      {
        name: '净流入',
        data: props.chartData.netflow
      }
    ]
  })
}

watch(() => props.year, () => {
  nextTick(updateChart)
})

watch(() => props.chartData, () => {
  nextTick(updateChart)
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件销毁时清理chart
defineExpose({
  dispose: () => {
    if (chart) {
      chart.dispose()
      chart = null
    }
    window.removeEventListener('resize', handleResize)
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 